package cube.io.file.zip;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import cube.data.util.DataUtil;
import cube.io.file.FileWriter;
import cube.utils.FileUtil;
import cube.utils.StringUtil;

/**
 * 压缩解压工具
 * 
 * @author abiao
 */
public class ZipUtil {

    /**
     * 解压zip中指定文件到path路径
     */
    public static void unzip(String zip, String file, String path) {
        unzip(zip, new String[] { file }, path);
    }

    /**
     * 解压zip中指定文件到path路径
     */
    public static void unzip(String zip, String[] files, String path) {
        if (!argsValid(zip, path)) {
            return;
        }
        dealZipStream(zip, files, path);
    }

    /**
     * 对压缩流进行处理
     */
    private static void dealZipStream(String zip, String[] files, String path) {
        try {
            FileInputStream fis = new FileInputStream(zip);
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry e = null;
            int unzip = 0;
            while ((e = zis.getNextEntry()) != null) {
                if (StringUtil.equalsOne(e.getName(), files)) {
                    unzipFile(zis, getUnzipName(path, e.getName()));
                    unzip++;
                    if (unzip == files.length) {
                        break;
                    }
                }
            }
            zis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取解压文件名称
     */
    private static String getUnzipName(String path, String name) {
        String dir = FileUtil.formatPathEndWithSEP(path);
        if (!FileUtil.existPath(dir)) {
            FileUtil.mkdir(dir);
        }
        return dir + FileUtil.getBaseName(name);
    }

    /**
     * 检查参数是否有效
     */
    private static boolean argsValid(String zip, String path) {
        if (!FileUtil.exist(zip)) {
            System.out.println("压缩文件" + zip + "不存在！");
            return false;
        }
        return true;
    }

    /**
     * 将解压流写入到文件
     */
    private static void unzipFile(ZipInputStream zis, String dst) {
        try {
            FileWriter fw = new FileWriter(dst);
            byte[] buff = new byte[1024];
            int size;
            while ((size = zis.read(buff)) != -1) {
                fw.write(DataUtil.copy(buff, 0, size));
            }
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
